package net.sf.midollo.net.protocol.multitunnel.server;

import java.io.IOException;
import java.io.InterruptedIOException;

import net.sf.midollo.io.IOStream;
import net.sf.midollo.net.protocol.multitunnel.MultiTunnelSession;

public class MultiTunnelServer extends MultiTunnelSession {

  protected final MultiTunnelServerFactory factory;
  protected IOStream ioStream;
  protected Thread threadServer;

  public MultiTunnelServer(MultiTunnelServerFactory factory, int sessionId, IOStream ioStream, int bufSize) throws IOException {
    super(factory, sessionId, ioStream, bufSize);
    this.factory = factory;
    this.ioStream = ioStream;
    this.threadServer = new Thread(this);
    this.threadServer.start();
  }

  public void destroySession() throws IOException {
    super.destroySession();
    disconnect();
  }

  public void disconnect() throws IOException {
    try {
      if (this.ioStream != null)
        this.ioStream.close();
    } finally {
      this.ioStream = null;
      try {
        if (this.threadServer != null)
          this.threadServer.join();
      } catch (InterruptedException ex) {
        if (this.error == null)
          this.error = new InterruptedIOException(ex.toString());
      } finally {
        this.threadServer = null;
      }
    }
  }
}
